<template>
  <div w-full h-full flex flex-row>
    <div class="uploadWrap h-full w-1/2  ">
      <div class="buttonWrap w-full text-right">
        <div class="inline" v-if="modelName !== ''">已选择模型：{{ modelName }}</div>
        <el-button type="primary" style=" margin: 10px; width: 150px;" @click="chooseModel">选择模型 </el-button>
      </div>
      <el-dialog v-model="dialogTableVisible" width="1350" title="模型选择">
        <div class="search flex items-end">
          <el-input class="!w-45 !h-8" v-model="search" size="small" @blur="" placeholder="输入模型名称关键字查询" />
          <el-button class="ml-3" @click="searchModelSet">查询</el-button>
          <el-button @click="resetData">重置</el-button>
        </div>
        <el-table ref="multipleTableRef" @row-click="getRowDataByClick" :data="tableData" height="650"
          style="font-size: 15px">
          <el-table-column width="210" prop="runId" align="center" label="模型id" />
          <el-table-column width="110" :show-overflow-tooltip="true" prop="runName" label="模型名称">
          </el-table-column>
          <el-table-column width="210" :show-overflow-tooltip="true" prop="description" align="center" label="模型描述" />
          <el-table-column width="180" prop="duration" align="center" label="持续时间" />
          <el-table-column width="110" prop="status" align="center" label="状态"> </el-table-column>
          <el-table-column sortable prop="startTime" align="center" width="250px" label="创建时间" />
          <el-table-column sortable prop="endTime" align="center" width="250px" label="结束时间" />
          <el-table-column prop="lifecycleStage" align="center" label="操作"> </el-table-column>
        </el-table>
        <el-pagination class="!justify-center" v-model:current-page="currentPage" v-model:page-size="pageSize"
          :size="size" :disabled="false" :background="true" layout="prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" />
      </el-dialog>
      <!-- :on-change="changeFile" -->
      <el-upload :headers="uploadHeader" :limit="1" :on-exceed="handleExceed" :multiple="false"
        v-model:file-list="fileList" :on-success="uploadSuccess" class="upload-demo h-[81%]" drag
        :before-upload="beforeUpload" action="/admin-api/infra/file/upload">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          文件拖到此处or<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip !mt-8">
            仅支持上传excel文件！
          </div>
        </template>
      </el-upload>
      <div class="submitReq w-full text-center !mt-2.5">
        <label for="showWay" class="mr-3">呈现方式</label>
        <el-select v-model="commitObject.returnType" placeholder="请选择">
          <el-option v-for="item in returnType_options" :key="item.label" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <div class="showReferece mt-3">
          <label for="showWay" class="mr-3">趋势参照</label>
          <el-select v-model="commitObject.refer" placeholder="请选择">
            <el-option v-for="item in commitObject.labels" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </div>
        <div class="btn text-right -mt-16">
          <el-button type="primary" class="ml-2" style=" width: 150px;" @click="startPredict">开始预测</el-button>
        </div>

      </div>
    </div>
    <div class="showWrap flex-1 h-full">
      <div class="d2 w-full h-full " ref="d2"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import option from '@/utils/echarts/threeDimension'
import { getToken } from '@/utils/cache/cookies';
import { genFileId } from 'element-plus'

const fileList = ref<UploadUserFile[]>([])
let search = ref('')
let fileName = ref('')
let modelName = ref('')
let currentPage = ref(1)
let pageSize = ref(10)
let size = 'default'
let total = ref(0)

let uploadHeader = {
  Authorization: 'Bearer ' + getToken()
}

let params = {
  runName: '',
  pageNo: currentPage.value,
  pageSize: pageSize.value,
  isAsc: false,
  orderBy: "runName"
}
let option2D = ref(option)
let d2 = ref()
let returnType_options = ref([
  { label: '图表展示', value: 'display' },
  { label: '文件下载', value: 'file' },
])
let commitObject = ref({
  runId: '',
  filePath: '',
  sortOrder: 'desc',
  dataType: 'excel',
  tableName: '',
  compositeConfig: [] as any,
  features: [] as any,
  labels: [] as any,
  returnType: '',
  refer: ''
})
let filePath = ref('')
let dialogTableVisible = ref(false)
let { proxy } = getCurrentInstance() as any
let tableData = ref()

const searchModelSet = () => {
  params.runName = search.value
  query()
}

const resetData = () => {
  params.runName = ''
  query()
}

// 处理  文件覆盖前一个上传的文件
const handleExceed: UploadProps['onExceed'] = (files) => {
  fileList.value = []
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  fileList.value.push(file)
}

const startPredict = () => {
  if (fileList.value.length == 0) {
    ElMessage.warning('请上传正确格式的文件后在预测！')
    return;
  } else if (commitObject.value.returnType == '' || commitObject.value.refer == '') {
    ElMessage.warning('请选择预测呈现结果以及趋势参照后操作！')
    return;
  }
  else {
    let url = '/admin-api/wpes/model/bpnnPredict'
    proxy.$http.post(url, commitObject.value).then((p) => {
      if (p.data.code == 1010) {
        ElMessage.info(`${p.data.msg}${p.data.data.errorMessage}`)
        return;
      }
      if (p.data.code == 200 || p.status == 200) {
        ElMessage.success('预测成功，等待结果展示！')
        if (commitObject.value.returnType == 'file') {
          let data = "\ufeff" + p.data
          const a = document.createElement("a")
          const blob = new Blob([data], { type: 'text/csv,charset=UTF-8' })
          const href = window.URL.createObjectURL(blob)
          a.href = href
          let fileName = "predict.csv"
          a.download = fileName
          ElMessage.success("下载正在进行中，请稍后！")
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(href)
          return
        }
        let { dimMsg, features, predictLabels } = p.data.data
        let set: string[] = [];
        let dimMsgKeys = Object.keys(dimMsg)
        let featuresKeys = Object.keys(features)
        let predictLabelsKeys = Object.keys(predictLabels)
        let predictLabelsValue = Object.values(predictLabels) as any[]
        let dataSource = [];
        option2D.value.dataset.dimensions = []
        option2D.value.dataset.source = []
        predictLabelsKeys.forEach(k => {
          option2D.value.dataset.dimensions.push(k)
          // 存入对应的key  x=> 'x' y => 'y'
          set.push(k)
        })
        dimMsgKeys.forEach(k => {
          option2D.value.dataset.dimensions.push(k)
          set.push(k)
        })
        featuresKeys.forEach(k => {
          option2D.value.dataset.dimensions.push(k)
          set.push(k)
        })
        dataSource.push(set)
        if (predictLabelsValue.length > 0) {
          predictLabelsValue.forEach(p => {
            p.forEach((item: number, index: number) => {
              let t = [] as any;
              predictLabelsKeys.forEach(k => {
                t.push(predictLabels[k][index])
              })
              dimMsgKeys.forEach(k => {
                t.push(dimMsg[k][index])
              })
              featuresKeys.forEach(k => {
                t.push(features[k][index])
              })
              dataSource.push(t)
            })
          })

          //对接数据源
          // console.log(dataSource)
          option2D.value.dataset.source = dataSource
          let maxmin = findMinMax(dataSource)
          let idx = set.findIndex(s => {
            return s == commitObject.value.refer
          })
          // console.log(maxmin, idx, set)
          if (idx >= 0) {
            option2D.value.visualMap[0].text = [set[idx]]
            option2D.value.visualMap[0].min = maxmin[idx].min
            option2D.value.visualMap[0].max = maxmin[idx].max
            option2D.value.visualMap[0].dimension = idx
            let e = [] as any
            set.forEach((s, i) => {
              if (featuresKeys.length > 3) {
                if (['x', 'y', 'z'].includes(s)) {
                } else {
                  e.push(i)
                }
              } else {
                e.push(i)
              }
            })
            option2D.value.series[0].encode.tooltip = e
          }
          console.log(option2D.value)
          proxy.$dom1 && proxy.$dom1.setOption(option2D.value)
        } else { // 输出数组为空

        }
      }
    })
  }
}
function findMinMax(arr) {
  const result = [];

  // 获取子元素数组的长度
  const length = arr[0].length;

  // 遍历每个子元素数组下标
  for (let i = 0; i < length; i++) {
    let min = arr[1][i];
    let max = arr[1][i];

    // 遍历数组，找出每个子元素下标一样的最大值和最小值
    for (let j = 1; j < arr.length; j++) {
      if (arr[j][i] < min) {
        min = arr[j][i];
      }
      if (arr[j][i] > max) {
        max = arr[j][i];
      }
    }

    // 将结果添加到结果数组中
    result.push({ max, min });
  }

  return result;
}
const getRowDataByClick = (row: any) => {
  const { runId, status, id } = row
  if (status == 'FAILED' || status == 'RUNNING' || status == 'ERROR') {
    ElMessage.warning('该模型不是完成或者终止状态，不能用于预测！')
    return;
  } else {
    let url = '/admin-api/wpes/runResult/get'
    let params = { id }
    proxy.$http.get(url, { params }).then((v) => {
      if (v.data.code == 0) {
        let config = JSON.parse(v.data.data.netConfig);
        commitObject.value.runId = runId
        commitObject.value.features = config.features
        commitObject.value.labels = config.labels
        // commitObject.value.compositeConfig = []
        dialogTableVisible.value = false
        modelName.value = row.runName
        ElMessage.success('已选择模型')
      }
    }).catch((e) => {
      console.log(e)
      ElMessage.warning('本次运行结果有错误，无法查看！')
    })
  }
}
function query() {
  let url = "/admin-api/wpes/runResult/page"
  proxy.$http.get(url, { params }).then((v) => {
    if (v.data.code == 0) {
      total.value = v.data.data.total
      tableData.value = v.data.data.list
    }
  })
}
const handleCurrentChange = (e) => {
  params.pageNo = e
  query()
}

const chooseModel = () => {
  dialogTableVisible.value = true
  query()
}
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let extension = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1);
  if (extension === 'csv' || extension === 'xls' || extension === 'xlsx') {
    fileName.value = rawFile.name
    return true
  } else {
    ElMessage.error('文件格式不是excel类文件，请检查！')
    fileList.value = []
    return false;
  }
}
const uploadSuccess = (f: any) => {
  if (f.code === 0) {
    ElMessage.success("上传成功！")
    filePath.value = f.data.replace('127.0.0.1', '172.30.32.7')
    commitObject.value.filePath = filePath.value
  }
}

onMounted(() => {
  if (d2.value) {
    proxy.$dom1 = proxy.$echarts.init(d2.value)
    proxy.$dom1 && proxy.$dom1.setOption(option2D.value)
  }
})

</script>

<style lang='scss' scoped>
:deep(.el-dialog__body) {
  padding: 10px 25px 35px 25px;
}

:deep(.el-upload) {
  height: 100% !important;

  &>.el-upload-dragger {
    height: 100% !important;
    display: flex;
    align-items: center;
    flex-direction: row;
    justify-content: center;
  }
}
</style>
